import table_view from './../../views/table/index';
import page_view from './../../views/table/page';
var events = require('events');
var template = require('template');
var json = require('{polyfill}/json');
var paging = require('paging');
var message = require('{layer}/message');
var layer = require('layer')
var dict = {}, resizing;
return events({
    more:false,
    pageParam:null,
    events:{
        'click .g-top-view .f-last-btn a':'showMore',
        'click .g-top-view .m-slide-last-item .select-result':'selectResult',
        'mousemove .g-table-view .g-table-thead th':'draps',
        'mouseleave .g-table-view .g-table-thead th':'mouseleave',
        'mousedown .g-table-view .g-table-thead th':'mousedown',
        'click .g-table-view .g-table-thead th':'clickSort',
        'click .g-table-view .g-table-body tr':'checkBox',
        'click .g-table-view .g-table-fixed .g-table-thead .table-cell-check':'checkAll',
        'mouseover .g-table-view .g-table-body tr':'addclass',
        'mouseleave .g-table-view .g-table-body tr':'reomveclass',
        'mousemove':'doc_mousemove',//document绑定事件
        'mouseup':'doc_mouseup',//document绑定事件
        'click .g-right-container .selec-show':'showSelectNum',
        'click .g-right-container .m-selec-item li':'selectPageNum',
    },
     showMore:function(e,elem) {
         var that = this;
         elem.find('.iconfont').hide()
        if(this.more){
            elem.find('.down').show()
            $('.m-slide-fun').stop().slideUp(function(){that.initTableCSS()});
        } else {
            elem.find('.up').show()
            $('.m-slide-fun').stop().slideDown(function(){that.initTableCSS()})
        }
        this.more =! this.more;
    },
    draps:function(e,elem) {//拖拽调整宽度   
        var othis = elem,
            oLeft = othis.offset().left,
            pLeft = e.clientX - oLeft;
        if(dict.resizeStart){
            return;
        }
        
        dict.allowResize = othis.width() - pLeft <= 10; //是否处于拖拽允许区域
        $('body').css('cursor', (dict.allowResize ? 'col-resize' : ''));
    },
    mouseleave:function(e,elem) {
        var othis = elem;
        if(dict.resizeStart) return;
        $('body').css('cursor', '');
    },
    mousedown:function(e,elem) {
        var othis = elem;
        if(dict.allowResize){
            var field = othis.data('field');
            e.preventDefault();
            dict.resizeStart = true; //开始拖拽
            dict.offset = [e.clientX, e.clientY]; //记录初始坐标
            this.getCssRule($('.g-table-view'),field, function(item){
                var width = item.style.width || othis.outerWidth();
                dict.rule = item;
                dict.ruleWidth = parseFloat(width);
                dict.minWidth = othis.data('minwidth') || '80';
            });
        }
    },
    doc_mousemove:function(e,elem) {//拖拽改变表格大小
        if(dict.resizeStart){
            e.preventDefault();
            if(dict.rule){
                var setWidth = dict.ruleWidth + e.clientX - dict.offset[0];
                if(setWidth < dict.minWidth) setWidth = dict.minWidth;
                dict.rule.style.width = setWidth + 'px';
                $('.g-table-fixed').height($('.g-table-ui')[0].scrollHeight)
            }
            resizing = 1
        }
    },
    doc_mouseup:function(e,elem) {//鼠标左键弹起初始化 dict
        if(dict.resizeStart){
            dict = {};
            $('body').css('cursor', '');
        }
        if(resizing === 2){
            resizing = null;
        }
    },
    checkBox:function(e,elem) {
        if($('.g-table-fixed .g-table-body .m-table-ui').hasClass('table-tr-info')) {
            this.showInfo(e,elem);
            return;
        }
        var $index = elem.index(),checkLen, len = 0;
        var allCheck = $('.g-table-fixed .g-table-thead .table-cell .iconfont').addClass('checked');
        var clickDom = $('#tfixData tr');
        var checkDom = clickDom.eq($index).find('input[type=checkbox]'),
            iconDom = clickDom.eq($index).find('.iconfont');
        var isCheck = checkDom.prop('checked');
        if(isCheck) {
            checkDom.prop('checked',false);
            iconDom.removeClass('checked');
        } else {
            checkDom.prop('checked',true);
            iconDom.addClass('checked');
        };
        len = clickDom.length;
        checkLen = clickDom.find('.checked').length;
        len === checkLen ? allCheck.addClass('checked') : allCheck.removeClass('checked');
    }, 
    checkAll:function(e,elem) {
        var isAllChecked = elem.find('.iconfont'),checkInput = $('#tfixData tr input[type=checkbox]'),iconfont = $('#tfixData tr .iconfont');
        if(isAllChecked.hasClass('checked')) {
            checkInput.prop('checked',false);
            iconfont.removeClass('checked');
            isAllChecked.removeClass('checked')
        } else {
            checkInput.prop('checked',true);
            iconfont.addClass('checked');
            isAllChecked.addClass('checked')
        }
    },
    showInfo:function(e,elem) {
        var $index = elem.index();
        var checkDom = $('#tfixData tr').eq($index).find('.iconfont');
        var url = checkDom.data('val');
        url ? window.open(url,'','width=800px,height=600px,left=50%,menubar=no,top=50px') : message('error','还没开票呢~你想瞅啥');
    },
    addclass:function(e,elem) {
        var othis = elem,index = othis.index();
        $('.g-table-body tr').eq(index).addClass('m-tr-hover');
        $('.g-scroll-table tr').eq(index).addClass('m-tr-hover');
    },
    reomveclass:function(e,elem) {
        var othis = elem,index = othis.index();
        $('.g-table-body tr').eq(index).removeClass('m-tr-hover');
        $('.g-scroll-table tr').eq(index).removeClass('m-tr-hover');
    },
    showSelectNum:function(e,elem) {
        var dis = $('.m-selec-item').css('display');
        if(dis === 'block') {
            $('.selec-show .bd-sin').removeClass('un-bd-sin');
            $('.m-selec-item').hide()
        } else {
            $('.selec-show .bd-sin').addClass('un-bd-sin');
            $('.m-selec-item').show()
        }
    },
    selectPageNum:function(e,elem) {
        $('.m-selec-item').hide();
        $('.m-selec-item li').removeClass('f-selected');
        $('.selec-show .bd-sin').removeClass('un-bd-sin')
        elem.addClass('f-selected')
        var $text = elem.text();
        $('.select-txt').text($text);
        this.pageParam.param.pCount = $text;
        this.curCount()
    },
    selectResult:function(e,elem) {
        var param = $('#seldctForm').serializeArray(),i,len = param.length,newObj = {};
        for(i=0;i<len;i++) {
            newObj[param[i].name]=param[i].value
        }
        var times = newObj.time;
        newObj['startTime'] = times && times.split('至')[0]
        newObj['endTime'] = times && times.split('至')[1] || '';
        var option = this.pageParam
        this.pageParam.param = $.extend({}, option.param, newObj);
        this.curCount()
    },
    noEvents: function(e,elem) {
        var that = this, initHeight = $('.g-table-ui .g-table-body').height(), fixedDom = $('.g-table-fixed');
        if(!fixedDom.length) {
            return
        }
        $('.g-scroll-table').on('scroll',function(){
            var othis = $(this),
            scrollTop = othis.scrollTop();
            $('.g-table-fixed .g-table-body').scrollTop(scrollTop);
        });
        $(window).on('resize',function() {
            that.initTableCSS(initHeight)
        });
    },
    getCssRule:function(elem,field,callback){//重置样式
        var style = elem.find('style')[0],
            sheet = style.sheet || style.styleSheet || {},
            rules = sheet.cssRules || sheet.rules;
        Nui.each(rules, function(item, i){
            if(item.selectorText === ('.table-cell-'+ field)){
                return callback(item), true;
            }
        });
    },
    /**
     * @param data {后台返回数据}
     */
    init:function(elem,data,param) {
        var option = {//表格默认配置
            callback:'',
            opt:'',
            url:'',
            param:{
                pCount:15
            }
        };
        
        option = $.extend({}, option, param);
        this.pageParam = option;
        this.pageParam.param.pCount = 15;
        this.render(elem,data,option);
        // this.updateSelectCss();
    },
    initTableCSS:function(initHeight) {
        if(this.more) {
            this.updateSelectCss();
        }
        var conDom = $('.g-right-container'),topDom = $('.g-top-view'),tableDom = $('.g-table-view');
        var cheight = conDom.height(),tpheight = topDom.height();

        topDom.length? tableDom.css('height',(cheight-tpheight-50-15)+'px') : tableDom.css('height',(cheight-tpheight-50)+'px');
        $('.g-table-fixed').height($('.g-table-ui')[0].scrollHeight);
    },
    updateSelectCss:function() {
        var conDom = $('.m-slide-con'), item= $('.m-slide-con .m-slide-item'), len = item.length, i;
        for(i = 0;i<len;i++) {
            var itemWidth = item.eq(i).find('.m-slide-c').width()-1;
            var leftStatic = item.eq(i).find('.f-label-title').outerWidth(true) ;
            // console.log(itemWidth,leftStatic)
            item.eq(i).find('.m-self-select').width(itemWidth-leftStatic)
        }
    },
    render:function(elem,data) {
        var that = this;
        elem.html(template.render(table_view, data));
        var pages = data.tabHead.nopage;
        $('.g-right-container').append(template.render(page_view,{nopage:pages}));
        that.initTableCSS();
        that.noEvents();
        that.curCount();
    },

    curCount:function() {
        var that = this,opt = that.pageParam;
        $.paging({
            url:opt.url,
            condition:opt.param,
            pCount:opt.param.pCount,
            ajax:{
                method:'post',
                // data:opt.param,
                // contentType:'application/json;charset=utf-8'
            },
            wrap:$('#paging1'),
            echoData:function(data,t){
                if(data.result === 'success') {
                    data.aCount = data.data.rowCount || data.data.aCount || data.data.total || 0;
                    $('.rows-count').text('共有'+data.aCount+'条数据')
                    opt.callback && opt.callback(data);
                } else {
                    message('error', data.message)
                }
            }
        })
    }
})